#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "Thread.hpp"

const static int defaultbuffersize = 1024;

void Usage(std::string porcess)
{
    std::cout << "usage : \n\t" << porcess << " localip localport " << std::endl;
}

class ThreadData
{
public:
    ThreadData(int socketfd, struct sockaddr_in &server)
        : _sockfd(socketfd), _server(server)
    {
    }
    ~ThreadData()
    {
        close(_sockfd);
    }

public:
    int _sockfd;
    struct sockaddr_in _server;
};

void SenderRoutine(ThreadData &td)
{
    while (true)
    {
        std::cout << "Please Enter@";
        std::string massage;
        std::getline(std::cin, massage);
        ssize_t n = sendto(td._sockfd, massage.c_str(), massage.size(), 0, (struct sockaddr *)&(td._server), (socklen_t)sizeof(td._server));
        if (n < 0)
        {
            std::cout << "snedder error" << std::endl;
        }
    }
}

void RecverRoutine(ThreadData &td)
{
    while (true)
    {
        char buffer[defaultbuffersize];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t m = recvfrom(td._sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if (m < 0)
        {
            std::cout << " recvfrom error : " << strerror(errno) << std::endl;
            return;
        }
        buffer[m] = 0;
        std::cout <<  buffer << std::endl; //自带头部信息
    }
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    std::string ip = argv[1];
    uint16_t port = std::atoi(argv[2]);

    // 创建文件细节
    int _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_sockfd < 0)
    {
        lg(Fatal, "create socket Fail ! erron %d strerror : %s", errno, strerror(errno));
        return Socket_Err;
    }

    lg(Info, "socket create success ! sockfd : %d\n", _sockfd);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    ThreadData td(_sockfd, server);

    Thread<ThreadData> Sender("Sender", SenderRoutine, td);
    Thread<ThreadData> Recver("Recver", RecverRoutine, td);
    Sender.Start();
    Recver.Start();

    Sender.Join();
    Recver.Join();
    return 0;
}
